/********************************************************************************
 * Project Name		[JavaSE_Fundamentals]
 * File Name     	[TestPrintStream.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package io.api;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * java.io.PrintStream测试<br/>
 * 
 * PrintStream可以将任何的内容以字符串形式输出[调用toString方法]<br/>
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class TestPrintStream {

	public static void main(String[] args) throws Exception {
		PrintStream out = null;
		PrintStream err = null;

		try {
			out = new PrintStream(new FileOutputStream("src/__/out.txt", true));
			err = new PrintStream(new FileOutputStream("src/__/err.txt", true));

			// IO流重定向, 设置输出和错误的重定向
			System.setOut(out);
			System.setErr(err);

			int count = 0; // 输入了几个数字
			int total = 0; // 表示总数
			int avg = 0; // 表示平均数
			int number = 0; // 表示每次输入的数字
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String temp = br.readLine();
			while (temp != null && !"over".equalsIgnoreCase(temp)) {
				number = Integer.parseInt(temp);
				count++;
				total += number;
				avg = total / count;
				System.out
						.println(new String(("输入了" + count + "个数字, 总和为: " + total + "平均数为: " + avg).getBytes("UTF-8")));
				temp = br.readLine();
			}
			br.close();
		} catch (Exception e) {
			try {
				System.err.println(new String(("出错时间: " + new Date()).getBytes("UTF-8")));
				System.err.println(new String("出错信息为: ".getBytes("UTF-8")));
				e.printStackTrace(err); // 将异常信息重定向输出, 可视为log的做法
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				out.close();
				err.close();
			} catch (Exception e) {
				try {
					System.err.println(new String(("出错时间: " + new Date()).getBytes("UTF-8")));
					System.err.println(new String("出错信息为: ".getBytes("UTF-8")));
					e.printStackTrace(err);
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}
			}
		}
	}
}
